/**
 * Copyright 2011 Brigham Young University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.byu.nlp.classify;

import java.util.Random;

import org.apache.commons.math3.optimization.ConvergenceChecker;
import org.apache.commons.math3.optimization.PointValuePair;
import org.apache.commons.math3.random.RandomVectorGenerator;

import com.google.common.base.Preconditions;

import edu.byu.nlp.data.Dataset;
import edu.byu.nlp.data.LabeledInstance;
import edu.byu.nlp.ml.ClassifierFactory;
import edu.byu.nlp.ml.DifferentiableObjectiveFunctionFactory;
import edu.byu.nlp.ml.StochasticGradientDescent;

/**
/**
 * A {@code SupervisedLearner} that uses stochastic gradient descent for learning.
 * 
 * @see StochasticGradientDescent
 * 
 * @author rah67
 *
 */
public class OnlineSupervisedLearner implements SupervisedLearner {

	private final ClassifierFactory factory;
	private final StochasticGradientDescent<LabeledInstance> sgd;

	/**
	 * @param objectiveFunction the function to optimize
	 * @param learningRate the learning rate
	 * @param weightInitializer provides the initial weights
	 * @param random is the random number generator used to shuffle the data
	 * @param convergenceChecker criteria for convergence
	 * @param factory creates the classifiers from the weight vector
	 * 
	 * @throws NullPointerException if any of the arguments are null
	 * @throws IllegalArgumentException if learningRate <= 0.0
	 * 
	 * @see edu.byu.nlp.ml.RandomVectorGenerators
	 */
	public OnlineSupervisedLearner(DifferentiableObjectiveFunctionFactory<LabeledInstance> objectiveFunction,
			double learningRate, RandomVectorGenerator weightInitializer, Random rnd,
			ConvergenceChecker<PointValuePair> convergenceChecker, ClassifierFactory factory) {
		Preconditions.checkNotNull(factory);
		
		this.factory = factory;
		this.sgd = new StochasticGradientDescent<LabeledInstance>(objectiveFunction, learningRate, weightInitializer,
				rnd, convergenceChecker);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Classifier learn(Dataset<LabeledInstance> data) throws LearningException {
		double[] weights;
		try {
			weights = sgd.learnWeights(data);
		} catch (Exception e) {
			throw new LearningException(e);
		}
		return factory.newInstance(weights);
	}
}
